package com.tos.second.task;

import com.tos.second.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class OrdersTask {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    public void cleanExpiredOrders() {
        try {
            log.info("开始清理过期未支付订单...");
            // 设置过期时间为5秒
//            LocalDateTime expireTime = LocalDateTime.now().minusSeconds(5);
            LocalDateTime expireTime = LocalDateTime.now().minusMinutes(15);
            int deletedCount = ordersMapper.deleteExpiredUnpaidOrdersByTime(expireTime);
            if (deletedCount > 0) {
                log.info("清理过期未支付订单完成，共删除 {} 条订单", deletedCount);
                // 删除订单后清除相关缓存
                deleteRedisCaches();
            }
        } catch (Exception e) {
            log.error("清理过期未支付订单时发生错误", e);
        }
    }
    // 删除 Redis 缓存
    private void deleteRedisCaches() {
        // 定义需要删除的 Redis 缓存键
        List<String> aKeys = Arrays.asList(
                "newGoodsCache",
                "goodsCache",
                "user_goods",
                "home",
                "category_goods",
                "recGoods"
        );


        for (String key : aKeys) {
            Set<String> keys = redisTemplate.keys(key + ":*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                log.info("删除key成功");
            }
        }
    }
}
